package com.henry.album.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

import javax.imageio.ImageIO;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.util.ObjectUtils;

public class VedioUtil {

	public static final List<String> vedioSuffixArray = Arrays.asList("AVI", "MP4", "MOV", "MKV", "TS", "MTS", "M2TS",
			"M2T", "M4V", "VOB", "DAT", "WEBM", "3GP", "3G2", "TRP", "M2P", "TP", "M1V", "M2V", "MPEG", "MPG", "F4V",
			"FLV", "ASF");

	public static void main(String[] args) {

		// vedioThumbnails("D:/vv.mp4", "D:/bb.jpg");
	}

	public static boolean isVedio(String filename) {

		String suffix = getSuffix(filename).toUpperCase();

		if (vedioSuffixArray.contains(suffix)) {

			return true;
		}

		return false;
	}

	public static String getSuffix(String filename) {

		if (ObjectUtils.isEmpty(filename)) {
			return "";
		}

		if (!filename.contains(".")) {

			return "";
		}

		return filename.substring(filename.lastIndexOf(".") + 1, filename.length());

	}

	/**
	 * @param videofile 视频路径，精确到文件
	 * @param framefile 保存的目标路径，精确到文件
	 * @return
	 * @throws Exception
	 */
	public static boolean vedioThumbnails(String videofile, String framefile) {
		try {
			File targetFile = new File(framefile);
			FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
			try {
				ff.start();
				int lenght = ff.getLengthInFrames();
				int i = 0;
				Frame f = null;
				while (i < lenght) {
					// 过滤前5帧
					f = ff.grabFrame();
					if ((i > 48) && (f.image != null)) {
						break;
					}
					i++;
				}
				int owidth = f.imageWidth;
				int oheight = f.imageHeight;
				// 对截取的帧进行等比例缩放
				int width = 300;
				int height = (int) (((double) width / owidth) * oheight);
				Java2DFrameConverter converter = new Java2DFrameConverter();
				BufferedImage fecthedImage = converter.getBufferedImage(f);
				BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
				bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,
						null);
				ImageIO.write(bi, "jpg", targetFile);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("ImgBase64Util fetchFrame() error.");
			} finally {
				ff.stop();
				ff.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
